package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.config.OssProperties;
import com.itheima.service.OssService;
import lombok.extern.log4j.Log4j2;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author tcotk
 */
@Service
@Log4j2
public class OssServiceImpl implements OssService {
    @Resource
    private OssProperties ossProperties;

    @Override
    public String uploadFileAvatar(MultipartFile file) {

        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret());
        String fileName = file.getOriginalFilename();
        try {
            ossClient.putObject(ossProperties.getBucketName(), fileName, file.getInputStream());
        } catch (Exception e) {
            log.error("上传文件异常");
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        //把上传之后文件路径返回
        //需要把上传到阿里云oss路径手动拼接出来
        String url = ossProperties.getUrl() + "/" + fileName;
        log.info("url:{}", url);
        return url;


    }


    /**
     * 通过上传过来的文件来获取这个文件的扩展名
     */
    public String getExtensionName(String filename) {
        //通过 "."来分割这个文件
        String[] split = filename.split("\\.");
        //获取最后一个的值就是文件扩展名
        String extensionName = split[split.length - 1];
        return "." + extensionName;
    }

}
